package com.crazyread.controller;

import cn.hutool.core.map.MapUtil;
import com.crazyread.comment.lang.Result;
import com.crazyread.dao.UserAuthorityMapper;
import com.crazyread.dao.UserMapper;
import com.crazyread.imple.UserDetailsServiceImpl;
import com.crazyread.imple.UserServiceImpl;
import com.crazyread.model.domain.User;
import com.crazyread.model.domain.UserAuthority;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Date;
import java.util.List;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

@RestController
@RequestMapping("/user")
@Api(value = "用户管理 controller" ,tags = {"用户管理接口统计"})
public class AdminController {
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserServiceImpl userService;
    @Autowired
    UserAuthorityMapper userAuthorityMapper;
    @Autowired
    UserDetailsServiceImpl userDetailsService;


    /**
     * 获取所有用户
     */
    @GetMapping("/allUser")
    @ApiOperation(value = "获取所有用户")
    public Result allUser(){
        List<User> users = userMapper.selectAllUser();

        for (int i = 0 ;i<users.size() ; i++){
            User user = users.get(i);
            List<GrantedAuthority> grantedAuthorities = userDetailsService.getUserAuthority(user.getId());
            user.setAuthority(String.valueOf(grantedAuthorities));
        }
        return Result.succ(users);
    }


    /**
     * 获取用户信息接口
     * @param principal
     * @return
     */
    @GetMapping("/userInfo")
    @ApiOperation(value = "获取用户信息接口")
    public Result userInfo(Principal principal){
        User user = userMapper.selUserByUsername(principal.getName());
        return Result.succ(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("email", user.getEmail())
                .put("created", user.getCreated())
                .map()
        );
    }

    /**
     * 注册用户用BCryptPasswordEncoder给我们生成一个密码
     */
    @PostMapping("/register")
    @ApiOperation(value = "注册用户")
    public Result registerUser(@RequestParam("username") String username,
                               @RequestParam("password") String password,
                               @RequestParam("email") String email){
        //密码需要设置编码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //密码加密
        String pass = encoder.encode(password);

        //封装注册的用户信息
        User user1 = new User();
        user1.setUsername(username);
        user1.setPassword(pass);
        user1.setEmail(email);
        user1.setCreated(new Date());
        UserAuthority ua = new UserAuthority();
        try {
            userMapper.registerUser(user1);
            User user = userMapper.selUserByUsername(username);
            ua.setUserId(user.getId());
            ua.setAuthorityId(2l);
            userAuthorityMapper.addUserAuthority(ua);
            return Result.succ("注册成功");
        }catch (Exception e){
            log.println(e.getMessage());
            return Result.succ("注册失败");
        }

    }

    //删除用户
    @DeleteMapping("/delUser/{id}")
    @ApiOperation(value = "删除用户")
    public Result delUser(@PathVariable("id") int id ){
        try {
            userService.delUser(id);
            return Result.succ("删除成功");
        }catch (Exception e) {
            return Result.succ("删除失败");
        }
    }

    //修改用户
    @ResponseBody
    @PostMapping("/updateUser")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="用户Id",required=true,paramType="Integer"),
            @ApiImplicitParam(name="created",value="为空",required=false),
    })
    public Result updateUser(User user){
         //密码需要设置编码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //密码加密
        String pass = encoder.encode(user.getPassword());
        user.setPassword(pass);
        userService.updateUser(user);
        return Result.succ("修改成功");
    }

}
